//
//  ViewController.swift
//  TestCountdown
//
//  Created by BeeGo-MAC on 2020/12/9.
//  Copyright © 2020 BeeGo-MAC. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        view.addSubview(timeLabel)
        view.addSubview(button)
        
        
        GCDTimer.shared.scheduledDispatchTimer(WithTimerName: "timeLabel", timeInterval: 1, queue: .main, repeats: true) {
            
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let date = dateFormatter.date(from: "2020-12-09 16:19:35")
            let time = date?.timeIntervalSinceNow
            self.timeLabel.text = self.countdownTime(time: Int(time ?? 0))
        }
        
    }
    
    @objc func buttonAction(sender: UIButton) {
        var value = 1
        var intValue = value
        intValue += 1
        value = intValue
        print(value, Date())
    }
    
    func countdownTime(time: Int) -> String {
        guard time > 0 else {
            return "00:00"
        }
        let allTime: Int = time
        var minutes = 0
        var seconds = 0
        
        var minutesText = ""
        var secondsText = ""
        
        minutes = allTime % 3600 / 60
        minutesText = minutes > 9 ? "\(minutes)" : "0\(minutes)"
        
        seconds = allTime % 3600 % 60
        secondsText = seconds > 9 ? "\(seconds)" : "0\(seconds)"
        
        return "\(minutesText):\(secondsText)"
    }

    
    lazy var timeLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 50, y: 100, width: UIScreen.main.bounds.size.width - 100, height: 50))
        label.font = UIFont.systemFont(ofSize: 15, weight: .medium)
        label.textAlignment = .center
        return label
    }()
    
    lazy var button: UIButton = {
        let btn = UIButton(type: .custom)
        btn.frame = CGRect(x: 100, y: 150, width: 100, height: 50)
        btn.setTitle("点击事件", for: .normal)
        btn.backgroundColor = .red
        btn.addTarget(self, action: #selector(buttonAction(sender:)), for: .touchUpInside)
        return btn
    }()

}

